const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8082 })

const cmdList = [
  {
    type: 'success',
    content: '连接成功!',
    time: '21:35:22',
  },
  {
    type: 'info',
    content: 'cod 50ml',
    time: '21:35:22',
  },
  {
    type: 'warning',
    content: 'cod 偏高',
    time: '21:35:22',
  },
  {
    type: 'error',
    content: '断开连接!',
    time: '21:35:22',
  },
]

let sendCmdIndex = 0

wss.on('connection', function connection(ws) {
  console.log('A new client Connected!')
  ws.send('Welcome New Client!')
  //主动向前端发送消息
  setInterval(() => {
    ws.send(JSON.stringify(cmdList[sendCmdIndex]))
    sendCmdIndex += 1
    if (sendCmdIndex >= 4) {
      sendCmdIndex = 0
    }
  }, 300)

  ws.on('message', function incoming(message) {
    console.log('received: %s', message)

    // Echo the message back to the client
    ws.send(`Server received: ${message}`)
  })

  ws.on('close', function () {
    console.log('The client has disconnected.')
  })

  ws.on('error', function (error) {
    console.error('WebSocket error:', error)
  })
})

console.log('WebSocket服务已启动!--- ws://localhost:8082')
